package com.wjm.blog.core.config;

import com.wjm.blog.common.constant.CommonConst;
import com.wjm.blog.core.redis.RequestUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Feign调用时设置Header
 *
 * @author Ailos
 * @version 1.0
 * @date 2020/12/21 18:38
 */
@Configuration
public class FeignRequestInterceptor implements RequestInterceptor {

    @Value("${spring.application.name}")
    private String service;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 熔断器关闭, 或自定义 Hystrix 的隔离策略, 才能获取请求头
        ServletRequestAttributes attributes = RequestUtil.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            requestTemplate.header(CommonConst.USER_TOKEN, request.getHeader(CommonConst.USER_TOKEN));
//            requestTemplate.header(CommonEnum.Request.TOKEN, request.getHeader(CommonEnum.Request.TOKEN));
//            requestTemplate.header(CommonConst.CURRENT_USER_SITEID_KEY, request.getHeader(CommonConst.CURRENT_USER_SITEID_KEY));
            requestTemplate.header("SERVICE", service);
        }
    }
}